<template>
  <div class="app-container">
    <el-form class="query-wrapper" :model="queryParams" style="display: block;">
      <el-date-picker type="daterange" start-placeholder="Start date" end-placeholder="End date"
      format="YYYY-MM-DD" v-model="dateValue" class="ipt"/> 
    <!-- <el-select v-model="queryParams.vesselName" filterable clearable placeholder="choose Vessel" @change="selectVessel">
      <el-option :key="item.vesselName" :label="item.vesselName" :value="item.vesselName" v-for="item in vessels">
      </el-option>
    </el-select>
    &nbsp;&nbsp;
    <el-select v-model="queryParams.voyageNo" filterable clearable placeholder="choose voyage" @change="selectVoyage">
      <el-option :key="item.voyageNo" :label="item.voyageNo" :value="item.voyageNo" v-for="item in voyages">
      </el-option>
    </el-select>
    &nbsp;&nbsp;
    <el-select v-model="queryParams.pol" filterable clearable placeholder="choose Pol">
      <el-option :key="item.portName" :label="item.portName" :value="item.portName" v-for="item in pols">
      </el-option>
    </el-select>
    &nbsp;&nbsp;
    <el-select v-model="queryParams.pod" filterable clearable placeholder="choose Pod">
      <el-option :key="item.portName" :label="item.portName" :value="item.portName" v-for="item in pods">
      </el-option>
    </el-select>-->
    &nbsp;&nbsp;
    
    <el-button type="primary"  icon="search" @click="search">Search</el-button>
    <SearchReset :query-params="queryParams" @reset="resetQuery"></SearchReset> 
    &nbsp;&nbsp;
    <el-button type="primary" plain icon="upload" onclick="this.nextSibling.click()">Upload</el-button
        >
        <input
          id="upload-spec-file"
          type="file"
          accept=".xlsx"
          v-show="false"
          @change="uploadFile($event)"
		  v-hasPermi="['cargoList:upload']"
        />
        &nbsp;&nbsp;
    <!-- <el-button type="primary" @click="handlePrint">Export</el-button> -->
    &nbsp;&nbsp;
    </el-form>

    <!-- </div> -->
    <el-empty v-if="listData.length === 0" description="No Data" :image-size="100" />
    <div v-for="(item, index) in listData" :key="index" class="item-box">
      <h3 style="text-align: center"><strong>{{item.title}}</strong></h3>
      <el-row class="manifest-tip-item__wrapper">
        <el-col :span="6" class="manifest-tip-item">
          <span class="title"><strong>Pol：</strong></span>{{ item.polDetail }}
        </el-col>
        <el-col :span="6" class="manifest-tip-item">
          <span class="title"><strong>Date：</strong></span>{{ item.cargoDate }}
        </el-col>
      </el-row>
      <el-table :ref="el => (tableRefs[index] = el)" stripe :data="item.detail" style="width: 100%" 
        @sort-change="handleSortChange">        
        <el-table-column prop="channel" label=" Channel" width="150" />
        <el-table-column prop="collectionFrom" label="Collection From" width="150" />
        <el-table-column prop="shipper" label="Shipper" width="100"  show-overflow-tooltip/>
        <el-table-column prop="model" label="Model"   width="100"  show-overflow-tooltip/>
        <el-table-column prop="pol" label="POL"   width="100" />
        <el-table-column prop="pod" label="POD"   width="100" />
        <el-table-column prop="rate" label="RATE"   width="100" />
        <el-table-column prop="maker" label="MAKER"   width="200" show-overflow-tooltip/>
        <el-table-column prop="cargoType" label="Cargo Type"   width="200"  show-overflow-tooltip/>
        <el-table-column prop="fuelType" label="Fuel Type"   width="100" show-overflow-tooltip/>
        <el-table-column prop="measureLength" label="Length(m)"   width="100" show-overflow-tooltip/>
        <el-table-column prop="measureWidth" label="Width(m)"   width="100" show-overflow-tooltip/>
        <el-table-column prop="measureHeight" label="Width(m)"    width="100" show-overflow-tooltip/>
        <el-table-column prop="totalUnits" label="total units"    width="100" show-overflow-tooltip/>
        <el-table-column prop="unitWeight" label="Unit Weight"    width="100" show-overflow-tooltip/>
        <el-table-column prop="totalVolume" label="Total CBM"    width="100" show-overflow-tooltip/>
        <el-table-column prop="revenue" label="Revenue" width="100" />
        <el-table-column prop="status" label="Status"   width="120" /> 
        <el-table-column prop="remark" label="Remarks"     show-overflow-tooltip/>
      </el-table>
    </div>
    <pagination
    v-show="total > 0"
    :total="total"
    :page="queryParams.pageNum"
    :limit="queryParams.pageSize"
    @pagination="pageQuery"
    style="float: right"
  />

    <el-dialog class="edit_dialog" destroy-on-close draggable :title="dialogTitle" v-model="dialogFormVisible">
      <el-form :model="formParam" :rules="rules" ref="custForm">
        <el-row>
          <el-col :span="24">
            <el-form-item label="MARKS & NOS." label-width="220px" prop="marks" required>
              <el-input type="textarea" v-model="formParam.marks"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="DESCRIPTION OF GOODS" label-width="220px" prop="goodsDesc" required>
              <el-input type="textarea" v-model="formParam.goodsDesc"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="NO.& KIND OF PKGS" label-width="220px" prop="goodsDesc" required>
              <el-input-number v-model="formParam.totalUnits" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Unit" label-width="220px" prop="unit" required>
              <el-select v-model="formParam.unit">
                <el-option v-for="item in units" :key="item" :value="item" :index="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="REMARKS" label-width="220px" prop="remark">
              <el-input type="textarea" v-model="formParam.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">{{ $t("ship.button.cancel") }}</el-button>
          <el-button @click="resetForm" type="warning">{{ $t("ship.button.reset") }}</el-button>
          <el-button type="primary" @click="submitForm">{{ $t("ship.button.submit") }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>   
  <script lang="ts" setup>
  import { ref, onMounted, reactive } from "vue";  
  import service from "@/utils/request";  
  import { ElNotification, ElMessageBox } from "element-plus";    
  import { convertDate } from "@/utils/date" 

  import { useTablesDrag } from '@/hooks/useHooks';
const { proxy, tableRefs, initTableDrag } = useTablesDrag()

  const custForm = ref(null);
  const dialogTitle = ref("");
  const initForm = {
    id: null,
    title:null,
    polDetail:null,
    cargoDate:null,
    status: null,
    channel:null,
    shipper: null,
    collectFrom: null,
    pol:null,
    pod:null,
    maker:null,
    model: null,
    cargoDesc: null,
    cargoType: null,
    fuelType: null,
    measureLength: null,
    measureWidth: null,
    measureHeight: null,
    unitCbm: null,
    unitWeight: null,
    rate:null,
    revenue:null,
    totalUnits: null,
    totalVolume: null,
    totalWeight: null
  };
  
  const formParam = reactive(Object.assign({}, initForm));
  
  const total = ref(0);
  
  const rules = ref({}); 
  let vessels = reactive([] as any)
  let voyages = reactive([] as any)
  let pols = reactive([] as any)
  let pods = reactive([] as any)
  const dateValue = ref([new Date(new Date().getTime() - 3600 * 1000 * 24 * 30), new Date()])
  const queryParams = reactive({
    pageNum: 1,
    pageSize: 20,
    carrier: null,
    startDate: convertDate(dateValue.value[0]),
    endDate: convertDate(dateValue.value[1]),
    orderByColumn: undefined,
    isAsc: undefined,
  });
  
  const listData = ref([]);
  const refreshTable = async () => {
    if(dateValue.value != null){ 
      queryParams.startDate= convertDate(dateValue.value[0])
      queryParams.endDate = convertDate(dateValue.value[1])
    }else{
       queryParams.startDate= null
       queryParams.endDate= null
    }    

    let result = await service.get("/shipping/forwardCargo/getTable", { params: queryParams });
    listData.value = result.data;
    total.value = result.total 
    initTableDrag()
  };
  
  const dialogFormVisible = ref(false);
  
  const editClickEvent = (row: any) => {
    dialogTitle.value = "Update Forwarding Cargo";
    dialogFormVisible.value = true;
    isAdd = false;
    Object.keys(initForm).forEach((k) => (formParam[k] = row[k]));
  };
  
  let isAdd = false;
  
  const addClickEvent = () => {
    dialogTitle.value = "Add Forwarding Cargo";
    isAdd = true;
    dialogFormVisible.value = true;
    Object.assign(formParam, initForm);
  };
  
  
  
  const resetForm = () => {
    // @ts-ignore
    custForm.value.resetFields();
  };
  
  const submitForm = () => {
    // @ts-ignore
    custForm.value.validate(async (valid) => {
      if (!valid) {
        return;
      }
      formParam.unitCbm = (formParam.unitHeight * formParam.unitWeight * formParam.unitLength).toFixed(3) 
      formParam.totalVolume = (formParam.unitCbm*formParam.totalUnits).toFixed(3)
      formParam.totalWeight = (formParam.unitWeight * formParam.totalUnits).toFixed(2)
      
      await service[isAdd ? "post" : "put"]("shipping/forwardCargo", formParam);
      // @ts-ignore
      ElNotification.success({
        title: "Prompt information",
        message: "save successful!",
        position: "bottom-right",
      });
      dialogFormVisible.value = false;
      refreshTable();
    });
  };
  
  const pageQuery = async (e) => {
    queryParams.pageNum = e.page;
    queryParams.pageSize = e.limit;
    refreshTable();
  };
  
  const search = () => {
    refreshTable();
  };
   
  const resetQuery = (data:any) => {
    Object.assign(queryParams, data)
    listData.value = []
    total.value = 0
  }
  
  const uploadFile = async (event) => {
    if (event.target == null || event.target.files[0] == null) {
      return;
    }
    const formData = new FormData();
    formData.append("file", event.target.files[0]);
    await service["post"]("shipping/forwardCargo/uploadFile", formData);
  };
  
  const handleSortChange = async (column: any) => {
    queryParams.orderByColumn = column.prop;
    queryParams.isAsc = column.order; //动态取值排序顺序
    refreshTable();
  };
  
  const removeClickEvent = (id) => {
    ElMessageBox.confirm("Confirm to delete the data？", "Confirmation Information", {
      type: "warning",
      confirmButtonText: "Confirm",
      cancelButtonText: "Cancel",
    }).then(async () => {
      await service.delete(`shipping/forwardCargo/${id}`);
  
      refreshTable();
      // @ts-ignore
      ElNotification.success({
        title: "Prompt information",
        message: "Delete successfully!",
        position: "bottom-right",
      });
    });
  };
  
  onMounted(async () => {
    let result = await service.get("/shipping/schedule/getAllSchedule");
    if (result) {
      vessels = result.data;
      voyages = (vessels.find(item => item.vesselName == 'AICC HUANGHU') || {schedules: [] }).schedules;
    }
    //refreshTable();
  });
  </script>
  <style lang="scss" scoped>
  .el-table__expand-column .cell {
      display: block !important;
  }
  .mytable th{
  border:#333 !important;
  
  }
.item-box{
  padding: 24px;
}
.manifest-tip-item__wrapper{
  margin-bottom: 12px;
}
  </style>